package com.uxsino.commons.baseclass;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MenuLib implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    /**
     * 有哪些模块哪些资源
     * <module, <id, FnBlock>>
     */
    private static ConcurrentHashMap<String, ConcurrentHashMap<String, JSONObject>> authLib = new ConcurrentHashMap<String, ConcurrentHashMap<String, JSONObject>>();

    /**
     *
     * @return new instance, not ref
     */
    public static Map<String, ConcurrentHashMap<String, JSONObject>> menus(){
        return authLib;
    }

    public static synchronized void build(JSONObject module){
        if(module == null){
            return;
        }
        String moduleName = module.getString("module");
        if(Strings.isNullOrEmpty(moduleName)){
            return;
        }
        JSONArray menus = module.getJSONArray("menus");

        ConcurrentHashMap<String, JSONObject> modules =  authLib.get(moduleName);
        if(modules == null){
            modules = new ConcurrentHashMap<>();
            authLib .put(moduleName, modules);
        }
        if(menus != null && !menus.isEmpty()){
            for (int i = 0; i < menus.size(); i++) {
                JSONObject m = menus.getJSONObject(i);
                String id = m.getString("id");
                if(Strings.isNullOrEmpty(id)){
                    continue;
                }
                modules.put(id, m);
            }
        }
    }

    public static synchronized void build(ICreateMenu creator) {
        JSONObject obj = creator.create();
        build(obj);
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, ICreateMenu> beanMap = applicationContext.getBeansOfType(ICreateMenu.class);
        // 以下代码是将bean按照自己定的规则放入map中，这里我的规则是key：service.toString();value:bean
        // 调用时，参数传入service.toString()的具体字符串就能获取到相应的bean
        // 此处也可以不做以下的操作，直接使用beanMap,在调用时，传入bean的名称
        for (ICreateMenu creator : beanMap.values()) {
            build(creator);
        }
    }

}
